<template>
  <div class="user-management-container">
    <!-- Header Toolbar -->
    <div class="user-header">
      <h1>用户管理</h1>
      <div class="header-actions">
        <button class="refresh-btn" @click="refreshData" :disabled="loading">
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '加载中...' : '刷新' }}
        </button>
        <button class="add-btn" @click="createUser">
          添加用户
        </button>
      </div>
    </div>

    <!-- 用户表格 -->
    <div class="table-container" ref="tableContainerRef">
      <table class="user-table">
        <thead>
          <tr>
            <th>用户</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>手机号</th>
            <th>注册时间</th>
            <th class="action-col">角色</th>
            <th class="action-col">状态</th>
            <th class="action-col">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.userId" class="user-row">
            <td class="user-cell">
              <div class="user-avatar-info">
                <div class="avatar-small">
                  <img v-if="user.avatarUrl" :src="user.avatarUrl" :alt="user.username" @error="handleAvatarError" />
                  <span v-else>{{ user.username.charAt(0).toUpperCase() }}</span>
                </div>
                <div class="user-name">{{ user.nickname }}</div>
              </div>
            </td>
             <td class="user-name">{{ user.username }}</td>
            <td class="email-cell">{{ user.email }}</td>
            <td class="phone-cell">{{ user.phoneNo }}</td>
            <td class="date-cell">{{ formatDate(user.registerTime) }}</td>
            <td class="action-col">
              <span class="role-toggle" :class="{ 'role-admin': user.admin, 'role-user': !user.admin }"
                @click="toggleUserRole(user.userId, user.admin)">
                {{ user.admin ? '管理员' : '用户' }}
              </span>
            </td>
            <td class="action-col">
              <span class="status-toggle" :class="{ 'status-active': user.status, 'status-inactive': !user.status }"
                @click="toggleUserStatus(user.userId, user.status)">
                {{ user.status ? '激活' : '禁用' }}
              </span>
            </td>
            <td class="action-col">
              <button class="update-btn" @click="updateUser(user)" title="编辑用户">
                编辑
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-if="loading && page > 1" class="loading-more">
        <div class="loading-spinner"></div>
        <span>加载更多...</span>
      </div>

      <div v-if="!hasMore && users.length > 0" class="no-more-data">
        <span>已加载全部 {{ total }} 条记录</span>
      </div>

        <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载用户数据中...</p>
    </div>
    <!-- 空状态 -->
    <div v-else-if="users.length === 0" class="empty">
      <p>暂无用户数据</p>
    </div>
    </div>

    <!-- Add User Modal -->
    <div v-if="showAddModal" class="modal-overlay" @click="closeAddModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>添加用户</h3>
          <button class="close-btn" @click="closeAddModal">&times;</button>
        </div>
        
        <form @submit.prevent="submitAddForm" class="modal-form">
          <div class="form-group">
            <label for="add-username">用户名 *</label>
            <input 
              id="add-username"
              v-model="addForm.username" 
              type="text" 
              required 
              placeholder="输入用户名"
            />
          </div>
          
          <div class="form-group">
            <label for="add-email">邮箱 *</label>
            <input 
              id="add-email"
              v-model="addForm.email" 
              type="email" 
              required 
              placeholder="输入邮箱地址"
            />
          </div>
          
          <div class="form-group">
            <label for="add-phone">手机号</label>
            <input 
              id="add-phone"
              v-model="addForm.phoneNo" 
              type="tel" 
              placeholder="输入手机号"
            />
          </div>
          
          <div class="form-group">
            <label for="add-password">密码 *</label>
            <input 
              id="add-password"
              v-model="addForm.password" 
              type="password" 
              required 
              placeholder="输入密码"
            />
          </div>
          
          <div class="form-group checkbox-group">
            <label class="checkbox-label">
              <input 
                v-model="addForm.admin" 
                type="checkbox"
              />
              <span class="checkbox-text">设置为管理员</span>
            </label>
          </div>
          
          <div class="form-actions">
            <button type="button" @click="closeAddModal" class="cancel-btn">取消</button>
            <button type="submit" class="submit-btn" :disabled="addFormSubmitting">
              <span v-if="addFormSubmitting" class="loading-spinner"></span>
              {{ addFormSubmitting ? '添加中...' : '添加' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Edit User Modal -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>编辑用户</h3>
          <button class="close-btn" @click="closeEditModal">&times;</button>
        </div>
        
        <form @submit.prevent="submitEditForm" class="modal-form">
          <div class="form-group">
            <label for="edit-username">用户名 *</label>
            <input 
              id="edit-username"
              v-model="editForm.username" 
              type="text" 
              required 
              placeholder="输入用户名"
            />
          </div>
          
          <div class="form-group">
            <label for="edit-email">邮箱 *</label>
            <input 
              id="edit-email"
              v-model="editForm.email" 
              type="email" 
              required 
              placeholder="输入邮箱地址"
            />
          </div>
          
          <div class="form-group">
            <label for="edit-phone">手机号</label>
            <input 
              id="edit-phone"
              v-model="editForm.phoneNo" 
              type="tel" 
              placeholder="输入手机号"
            />
          </div>
          
          <div class="form-group checkbox-group">
            <label class="checkbox-label">
              <input 
                v-model="editForm.admin" 
                type="checkbox"
              />
              <span class="checkbox-text">设置为管理员</span>
            </label>
          </div>
          
          <div class="form-actions">
            <button type="button" @click="closeEditModal" class="cancel-btn">取消</button>
            <button type="submit" class="submit-btn" :disabled="editFormSubmitting">
              <span v-if="editFormSubmitting" class="loading-spinner"></span>
              {{ editFormSubmitting ? '更新中...' : '更新' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { invoke } from '@tauri-apps/api/core'

interface User {
  userId: number
  username: string
  nickname: string
  avatarUrl: string
  gender: number
  registerTime: string
  email: string
  phoneNo: string
  admin: boolean
  status: boolean
  createdAt: string
  updatedAt: string
}

const users = ref<User[]>([])
const loading = ref(false)
const error = ref('')
const page = ref(1)
const hasMore = ref(true)
const total = ref(0)
const tableContainerRef = ref<HTMLElement>()

// Modal states
const showAddModal = ref(false)
const showEditModal = ref(false)
const addFormSubmitting = ref(false)
const editFormSubmitting = ref(false)

// Form data
const addForm = ref({
  username: '',
  email: '',
  phoneNo: '',
  password: '',
  admin: false
})

const editForm = ref({
  userId: 0,
  username: '',
  email: '',
  phoneNo: '',
  admin: false
})

// 刷新数据
const refreshData = () => {
  console.log('刷新用户管理数据')
  page.value = 1
  hasMore.value = true
  loadUsers()
}

// 添加用户
const createUser = () => {
  console.log('打开添加用户对话框')
  resetAddForm()
  showAddModal.value = true
}

// 编辑用户
const updateUser = (user: User) => {
  console.log('打开编辑用户对话框:', user)
  editForm.value = {
    userId: user.userId,
    username: user.username,
    email: user.email,
    phoneNo: user.phoneNo,
    admin: user.admin
  }
  showEditModal.value = true
}

// Reset add form
const resetAddForm = () => {
  addForm.value = {
    username: '',
    email: '',
    phoneNo: '',
    password: '',
    admin: false
  }
}

// Close modals
const closeAddModal = () => {
  showAddModal.value = false
  resetAddForm()
}

const closeEditModal = () => {
  showEditModal.value = false
  editForm.value = {
    userId: 0,
    username: '',
    email: '',
    phoneNo: '',
    admin: false
  }
}

// Submit add form
const submitAddForm = async () => {
  try {
    addFormSubmitting.value = true
    
    console.log('[DEBUG] Submitting add user form:', addForm.value)
    
    const response = await invoke('create_user', {
      username: addForm.value.username,
      email: addForm.value.email,
      phoneNo: addForm.value.phoneNo,
      password: addForm.value.password,
      admin: addForm.value.admin
    })
    
    console.log('[DEBUG] Add user response:', response)
    
    if (response) {
      const parsedResponse = typeof response === 'string' ? JSON.parse(response) : response
      
      if ((parsedResponse.status === 1 || parsedResponse.status === true) && 
          (parsedResponse.code === 0 || parsedResponse.code === 200)) {
        console.log('[DEBUG] User added successfully')
        closeAddModal()
        refreshData()
        if (window.showToast) {
          window.showToast?.('用户添加成功', 'success')
        }
      } else {
        throw new Error(parsedResponse.msg || '添加用户失败')
      }
    } else {
      throw new Error('服务器无响应')
    }
  } catch (err) {
    console.error('[ERROR] Failed to add user:', err)
    if (window.showToast) {
          window.showToast?.(err instanceof Error ? err.message : '添加用户时发生错误', 'error')
        }
  } finally {
    addFormSubmitting.value = false
  }
}

// Submit edit form
const submitEditForm = async () => {
  try {
    editFormSubmitting.value = true
    
    console.log('[DEBUG] Submitting edit user form:', editForm.value)
    
    const response = await invoke('update_user', {
      userId: editForm.value.userId.toString(),
      username: editForm.value.username,
      email: editForm.value.email,
      phoneNo: editForm.value.phoneNo,
      admin: editForm.value.admin
    })
    
    console.log('[DEBUG] Update user response:', response)
    
    if (response) {
      const parsedResponse = typeof response === 'string' ? JSON.parse(response) : response
      
      if ((parsedResponse.status === 1 || parsedResponse.status === true) && 
          (parsedResponse.code === 0 || parsedResponse.code === 200)) {
        console.log('[DEBUG] User updated successfully')
        closeEditModal()
        refreshData()
        if (window.showToast) {
          window.showToast?.('用户更新成功', 'success')
        }
      } else {
        throw new Error(parsedResponse.msg || '更新用户失败')
      }
    } else {
      throw new Error('服务器无响应')
    }
  } catch (err) {
    console.error('[ERROR] Failed to update user:', err)
    if (window.showToast) {
      window.showToast?.(err instanceof Error ? err.message : '更新用户时发生错误', 'error')
    }
  } finally {
    editFormSubmitting.value = false
  }
}

const loadUsers = async (loadMore = false) => {
  if (!loadMore) {
    loading.value = true
    error.value = ''
  }

  try {
    const response:{status:number,data:{records:User[],total:number},msg:string} = await invoke('get_users', { page: page.value, size: 30 })

    if (response && response.status === 1 && response.data) {
      const newUsers = response.data.records || []
      total.value = response.data.total || 0

      if (loadMore) {
        users.value.push(...newUsers)
      } else {
        users.value = newUsers
      }

      hasMore.value = users.value.length < total.value
    } else {
      throw new Error(response?.msg || '获取用户数据失败')
    }
  } catch (err) {
    console.error('加载用户数据失败:', err)
    error.value = '加载用户数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const formatDate = (dateString: string): string => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const toggleUserRole = async (userId: number, currentRole: boolean) => {
  const newRole = !currentRole  // 直接取反：true -> false, false -> true
  const isAdminValue = newRole ? 1 : 0  // 转换为API期望的格式：1=管理员，0=普通用户

  try {
    const response = await invoke('switch_admin_role', { userId: userId.toString(), isAdmin: isAdminValue })
    if (response) {
      const parsedResponse = typeof response === 'string' ? JSON.parse(response) : response
      console.log('switch_admin_role response:', parsedResponse)

      // 根据实际响应格式处理：status为1表示成功，data为1或0，msg为提示消息
      if (parsedResponse.status === 1 && parsedResponse.code === 200) {
        const user = users.value.find(u => u.userId === userId)
        if (user) {
          user.admin = newRole  // 直接设置为新的布尔值
        }
        if (window.showToast) {
          window.showToast?.(`角色已更新为 ${newRole ? '管理员' : '用户'}`, 'success')
        }
      } else {
        throw new Error(parsedResponse?.msg || '更新角色失败')
      }
    } else {
      throw new Error('服务器无响应')
    }
  } catch (err) {
    console.error('更新用户角色失败:', err)
    if (window.showToast) {
      window.showToast?.('更新用户角色失败，请稍后重试', 'error')
    }
  }
}

const toggleUserStatus = async (userId: number, currentStatus: boolean) => {
  const newStatus = !currentStatus  // 直接取反：true -> false, false -> true
  const statusValue = newStatus ? 1 : 0  // 转换为API期望的格式：1=启用，0=禁用

  try {
    const response = await invoke('enable_user', { userId: userId.toString(), status: statusValue })
    if (response) {
      const parsedResponse = typeof response === 'string' ? JSON.parse(response) : response
      console.log('enable_user response:', parsedResponse)

      // 根据实际响应格式处理：status为1表示成功，data为1或0
      if (parsedResponse.status === 1 && parsedResponse.code === 200) {
        const user = users.value.find(u => u.userId === userId)
        if (user) {
          user.status = newStatus  // 直接设置为新的布尔值
        }
        if (window.showToast) {
          window.showToast?.(`状态已更新为 ${newStatus ? '激活' : '禁用'}`, 'success')
        }
      } else {
        throw new Error(parsedResponse?.msg || '更新状态失败')
      }
    } else {
      throw new Error('服务器无响应')
    }
  } catch (err) {
    console.error('更新用户状态失败:', err)
    if (window.showToast) {
      window.showToast?.('更新用户状态失败，请稍后重试', 'error')
    }
  }
}

const handleAvatarError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
  img.parentElement?.querySelector('span')?.removeAttribute('style')
}

const handleScroll = () => {
  if (!tableContainerRef.value) return

  const container = tableContainerRef.value
  const scrollTop = container.scrollTop
  const scrollHeight = container.scrollHeight
  const clientHeight = container.clientHeight

  // 当滚动到距离底部200px时加载更多（更容易触发）
  const threshold = 200
  if (scrollTop + clientHeight >= scrollHeight - threshold && hasMore.value && !loading.value) {
    console.log('Loading more users...', { page: page.value + 1 })
    page.value++
    loadUsers(true)
  }
}
const hanlderUserSearch = async (event: Event) => {
  const customEvent = event as CustomEvent
  const { query } = customEvent.detail || {}

  if (!query || query.trim() === '') {
    // 如果搜索框为空，重新加载所有用户
    await loadUsers()
    return
  }

  try {
    loading.value = true
    const response = await invoke('search_users', { username: query.trim() })

    if (response) {
      const parsedResponse = typeof response === 'string' ? JSON.parse(response) : response
      // 根据API响应格式处理：status为1表示成功，data为用户数组
      if (parsedResponse.status === 1 && parsedResponse.code === 200 && parsedResponse.data) {
        users.value = parsedResponse.data.map((user: any) => ({
          userId: user.userId,
          username: user.username,
          avatarUrl: user.avatarUrl || '',
          gender: user.gender === 1 ? '男' : (user.gender === 2 ? '女' : '未知'),
          registerTime: user.registerTime || user.createdAt,
          email: user.email || '',
          phoneNo: user.phoneNo || '',
          admin: user.admin || false,
          status: user.status || false
        }))

      } else {
        users.value = []
      }
    }
  } catch (err) {
    console.error('搜索用户失败:', err)
    if (window.showToast) {
      window.showToast?.('搜索用户失败，请稍后重试', 'error')
    }
    users.value = []
  } finally {
    loading.value = false
  }
}
onMounted(() => {
  loadUsers()


  window.addEventListener('global-search', hanlderUserSearch)
  // 使用 nextTick 确保 DOM 已渲染
  nextTick(() => {
    if (tableContainerRef.value) {
      tableContainerRef.value.addEventListener('scroll', handleScroll)
      console.log('Scroll listener attached')
    }
  })
})

onUnmounted(() => {
  if (tableContainerRef.value) {
    tableContainerRef.value.removeEventListener('scroll', handleScroll)
    window.removeEventListener('global-search', hanlderUserSearch)
  }
})
</script>

<style scoped>
.user-management-container {
  padding: 0;
  height: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--bg-primary);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
  box-sizing: border-box;
}

/* Header Toolbar 样式 */
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--bg-secondary);
  border-bottom: 1px solid var(--border);
  padding: 16px 20px;
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.user-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.refresh-btn,
.add-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.refresh-btn {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.refresh-btn:hover:not(:disabled) {
  background-color: var(--bg-card);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.add-btn {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
}

.add-btn:hover {
  background-color: var(--accent-primary-hover);
}

.loading,
.error,
.empty {
  text-align: center;
  padding: 60px 40px;
  color: var(--text-primary);
  background: var(--bg-card);
  backdrop-filter: blur(10px);
  border-radius: 0;
  border: 1px solid var(--border);
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid var(--border);
  border-top: 4px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error button {
  margin-top: 16px;
  padding: 10px 20px;
  background: var(--bg-tertiary);
  color: var(--accent-primary);
  border: 1px solid var(--border);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.error button:hover {
  background: var(--bg-card);
  transform: translateY(-1px);
}

.table-container {
  flex: 1;
  background: var(--bg-secondary);
  backdrop-filter: blur(10px);
  border-radius: 0;
  box-shadow: none;
  border: none;
  overflow-y: auto;
  position: relative;
  min-height: 0;
  padding-bottom: 80px;
  max-height: calc(100vh - 80px); /* 设置最大高度，确保在视口内 */
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid var(--border);
  border-top: 2px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.table-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-container::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb {
  background: var(--border-hover);
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: var(--accent-primary);
}

.user-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  min-width: 800px;
}

.user-table thead {
  background: var(--bg-tertiary);
  color: var(--text-primary);
  position: sticky;
  top: 0;
  z-index: 10;
}

.user-table th {
  padding: 16px 20px;
  text-align: left;
  font-weight: 600;
  font-size: 15px;
  white-space: nowrap;
  border-bottom: 2px solid var(--border);
  position: relative;
}

.user-table tbody tr {
  border-bottom: 1px solid var(--border);
  transition: all 0.3s ease;
  background: var(--bg-secondary);
}

.user-table tbody tr:hover {
  background: var(--bg-tertiary);
  transform: translateY(-1px);
  box-shadow: var(--shadow-hover);
}

.loading-more,
.no-more-data {
  padding: 20px;
  text-align: center;
  color: var(--text-secondary);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid var(--border);
  border-top: 2px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.user-table td {
  padding: 16px 20px;
  color: var(--text-primary);
  vertical-align: middle;
}

.user-avatar-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar-small {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: var(--gradient-primary);
  color: var(--text-inverse);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 600;
  flex-shrink: 0;
  box-shadow: var(--shadow-card);
}

.avatar-small img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.user-name {
  font-weight: 600;
  color: var(--text-primary);
}

.email-cell,
.phone-cell {
  font-size: 14px;
  color: var(--text-secondary);
}

.role-badge,
.status-badge {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.role-badge {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  border: 1px solid var(--border);
}

.role-badge.admin {
  background: var(--gradient-primary);
  color: var(--text-inverse);
  box-shadow: var(--shadow-card);
}

.status-badge {
  background: var(--accent-danger);
  color: var(--text-inverse);
  border: 1px solid var(--accent-danger);
}

.status-badge.active {
  background: var(--gradient-primary);
  color: var(--text-inverse);
  box-shadow: var(--shadow-card);
}

.date-cell {
  font-size: 14px;
  color: var(--text-secondary);
  white-space: nowrap;
}

@media (max-width: 768px) {
  .user-management-container {
    padding: 0;
  }

  .table-container {
    border-radius: 0;
    height: 100vh;
    padding-bottom: 60px;
  }

  .user-table {
    font-size: 13px;
  }

  .user-table th,
  .user-table td {
    padding: 12px 16px;
  }

  .user-avatar-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .avatar-small {
    width: 32px;
    height: 32px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .user-management-container {
    padding: 0;
  }

  .table-container {
    border-radius: 0;
    height: 100vh;
    padding-bottom: 50px;
  }

  .user-table {
    font-size: 12px;
  }

  .user-table th,
  .user-table td {
    padding: 10px 12px;
  }

  .role-badge,
  .status-badge {
    padding: 4px 8px;
    font-size: 11px;
  }
}

.user-table th.action-col {
  text-align: center;
  width: 80px;
}

.user-table td.action-col {
  text-align: center;
}

.role-toggle,
.status-toggle {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
  min-width: 60px;
  text-align: center;
}

.update-btn {
  display: inline-block;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: var(--accent-info);
  color: var(--text-inverse);
  min-width: 50px;
}

.update-btn:hover {
  background-color: var(--accent-info-hover);
  transform: translateY(-1px);
  box-shadow: var(--shadow-hover);
}

.role-toggle:hover,
.status-toggle:hover {
  transform: translateY(-1px);
  box-shadow: var(--shadow-hover);
}

.role-toggle.role-admin {
  background: var(--accent-warning);
  color: var(--text-inverse);
}

.role-toggle.role-user {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.status-toggle.status-active {
  background: var(--accent-success);
  color: var(--text-inverse);
}

.status-toggle.status-inactive {
  background: var(--accent-danger);
  color: var(--text-inverse);
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--bg-overlay);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: var(--bg-card);
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--border);
}

.modal-header h3 {
  margin: 0;
  color: var(--text-primary);
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.2s;
}

.close-btn:hover {
  color: var(--text-primary);
}

.modal-form {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: var(--text-primary);
  font-size: 14px;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 10px 12px;
  background-color: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 4px;
  color: var(--text-primary);
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: var(--accent-primary);
}

.checkbox-group {
  margin-bottom: 20px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-bottom: 0;
}

.checkbox-label input[type="checkbox"] {
  width: auto;
  margin-right: 8px;
  margin-bottom: 0;
}

.checkbox-text {
  color: var(--text-primary);
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
}

.cancel-btn,
.submit-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.cancel-btn {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.cancel-btn:hover {
  background-color: var(--bg-card);
}

.submit-btn {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
}

.submit-btn:hover:not(:disabled) {
  background-color: var(--accent-primary-hover);
}

.submit-btn:disabled {
  background-color: var(--bg-disabled);
  cursor: not-allowed;
  opacity: 0.6;
}

.submit-btn .loading-spinner {
  width: 14px;
  height: 14px;
}

/* Responsive adjustments */
@media (max-width: 600px) {
  .modal-content {
    width: 95%;
    margin: 10px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .cancel-btn,
  .submit-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>